from model.ssh_connector import SSHConnector
import time
from PySide6.QtWidgets import QDialog, QVBoxLayout, QTreeWidget, QTreeWidgetItem, QPushButton, QHBoxLayout, QLabel, QMessageBox
from PySide6.QtGui import QIcon
from PySide6.QtCore import QSize, Qt


class BrowserWidget(QDialog):
    """远程文件浏览器"""

    def __init__(self, server_info: dict, start_path="/", select_mode="both"):
        super().__init__()
        self.setWindowTitle(f"远程文件浏览器 - {server_info['ip']}")
        self.resize(900, 600)
        self.current_path = start_path
        self.selected_path = None
        self.select_mode = select_mode
        self.server_info = server_info

        self.ssh = SSHConnector()

        # 文件树
        self.tree = QTreeWidget()
        self.tree.setHeaderLabels(["名称", "大小 (KB)", "修改时间", "权限"])
        self.tree.setIconSize(QSize(20, 20))
        self.tree.itemClicked.connect(self.on_item_clicked)
        self.tree.itemDoubleClicked.connect(self.on_item_double_clicked)

        # 底部栏
        btn_layout = QHBoxLayout()
        self.path_label = QLabel("/")
        self.ok_btn = QPushButton("确定")
        self.cancel_btn = QPushButton("取消")
        self.ok_btn.clicked.connect(self.accept)
        self.cancel_btn.clicked.connect(self.reject)
        btn_layout.addWidget(self.path_label)
        btn_layout.addStretch()
        btn_layout.addWidget(self.ok_btn)
        btn_layout.addWidget(self.cancel_btn)

        layout = QVBoxLayout(self)
        layout.addWidget(self.tree)
        layout.addLayout(btn_layout)

        # 初始化刷新
        self.refresh()

    def refresh(self):
        """刷新当前目录"""
        self.tree.clear()
        self.path_label.setText(self.current_path)

        # 上级目录
        if self.current_path != "/":
            up_item = QTreeWidgetItem(["上一级"])
            up_item.setData(0, Qt.UserRole, {"path": "parent"})
            self.tree.addTopLevelItem(up_item)

        # 使用 SSHConnector 获取目录内容
        result = self.ssh.list_dir(self.server_info, self.current_path)
        if not result["status"]:
            QMessageBox.warning(self, "错误", f"读取目录失败: {result['error']}")
            return

        for f in result["files"]:
            icon = QIcon.fromTheme("folder") if f["is_dir"] else QIcon.fromTheme("text-x-generic")
            mtime = time.strftime("%Y-%m-%d %H:%M", time.localtime(f["mtime"]))
            item = QTreeWidgetItem([
                f["filename"],
                "" if f["is_dir"] else str(f["size"]),
                mtime,
                f["mode"]
            ])
            item.setIcon(0, icon)
            item.setData(0, Qt.UserRole, {
                "path": f"{self.current_path.rstrip('/')}/{f['filename']}",
                "is_dir": f["is_dir"]
            })
            self.tree.addTopLevelItem(item)

    def on_item_clicked(self, item, column):
        data = item.data(0, Qt.UserRole)
        if not data:
            return

        path = data.get("path")

        if path == "parent":
            self.current_path = "/".join(self.current_path.rstrip("/").split("/")[:-1]) or "/"
            self.refresh()
            return

        # 单击选中
        if self.select_mode in ("both", "file") or (data["is_dir"] and self.select_mode in ("both", "dir")):
            self.selected_path = path
            self.path_label.setText(f"选择: {self.selected_path}")

    def on_item_double_clicked(self, item, column):
        data = item.data(0, Qt.UserRole)
        if data and data.get("is_dir"):
            self.current_path = data["path"]
            self.refresh()

    def get_selected_path(self):
        return self.selected_path or self.current_path
